package com.superb.common.database.handler;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.superb.common.core.exception.SuperbException;
import com.superb.common.utils.StringUtils;
import com.superb.common.utils.HeardersUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.util.ClassUtils;

import java.util.Date;

/**
 * 新增/修改时的参数注入
 * @Author: ajie
 * @CreateTime: 2024-05-07 15:20
 */
@Slf4j
public class MybatisPlusMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        log.debug("mybatis plus start insert fill ....");
        fillValIfNullByName("createTime", new Date(), metaObject);
        fillValIfNullByName("tenantId", HeardersUtils.getTenantId(), metaObject);
        if (StringUtils.isBlank(HeardersUtils.getAuthentication())) {
            fillValIfNullByName("createBy", "NOTLOGIN", metaObject);
            fillValIfNullByName("organId", "NOTLOGIN", metaObject);
        } else {
            fillValIfNullByName("createBy", StpUtil.getLoginId(), metaObject);
            fillValIfNullByName("organId", HeardersUtils.getOrganizetionId(), metaObject);
        }
        // 删除标记自动填充
        fillValIfNullByName("del", 0, metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.debug("mybatis plus start update fill ....");
        fillValIfNullByName("updateTime", new Date(), metaObject);
        if (StringUtils.isBlank(HeardersUtils.getAuthentication())) {
            fillValIfNullByName("updateBy", "NOTLOGIN", metaObject);
        } else {
            fillValIfNullByName("updateBy", StpUtil.getLoginId(), metaObject);
        }

    }

    /**
     * 填充值，先判断是否有手动设置，优先手动设置的值，例如：job必须手动设置
     *
     * @param fieldName  属性名
     * @param fieldVal   属性值
     * @param metaObject MetaObject
     */
    private static void fillValIfNullByName(String fieldName, Object fieldVal, MetaObject metaObject) {
        // 0. 如果填充值为空
        if (fieldVal == null) {
            return;
        }

        // 1. 没有 set 方法
        if (!metaObject.hasSetter(fieldName)) {
            return;
        }
        // 2. 如果用户有手动设置的值
        Object userSetValue = metaObject.getValue(fieldName);
        if (StringUtils.isNotEmpty(userSetValue)) {
            return;
        }
        // 3. field 类型相同时设置
        Class<?> getterType = metaObject.getGetterType(fieldName);
        if (ClassUtils.isAssignableValue(getterType, fieldVal)) {
            metaObject.setValue(fieldName, fieldVal);
        }
    }
}
